<template>
	<view class="payment">
		<u-navbar ref="navbarRef" class="van-nav-bar" :placeholder="true" title="咨询订单" @leftClick="leftClick"
			:autoBack="false"></u-navbar>
		<view class="process">
			<u-steps :current="current" inactiveColor="#b0b0b0">
				<u-steps-item title="选择服务"></u-steps-item>
				<u-steps-item title="选择来访者"></u-steps-item>
				<u-steps-item title="提交订单"></u-steps-item>
				<u-steps-item title="确认支付"></u-steps-item>
			</u-steps>
		</view>
		<view class="cantainer" :style="{ height: domHeight }">
			<scroll-view class="scrollWrap" :enhanced="true" scroll-y :bounces="false" :show-scrollbar="false">
				<view class="dot-show">
					<image :src="$fullImageUrl(experInfo.avatarUrl)"></image>
					<view>
						<view>{{ experInfo.expertName }}</view>
						<view>{{ experInfo.title }}</view>
						<view>{{ experInfo.tags }}</view>
					</view>
					<view>正在预约中</view>
				</view>
				<view class="appointInfo">
					<view>预约信息</view>
					<view class="info">
						<view>服务名称:</view>
						<view v-if="dataObj.consultationType == 1">个人用户个体咨询</view>
						<view v-if="dataObj.consultationType == 2">个人用户家庭咨询</view>
					</view>
					<view class="info">
						<view>咨询方式:</view>
						<view v-if="dataObj.consultationMethod == 1">电话咨询</view>
						<view v-if="dataObj.consultationMethod == 2">线上语音</view>
						<view v-if="dataObj.consultationMethod == 3">线上视频</view>
						<view v-if="dataObj.consultationMethod == 4">当面咨询</view>
					</view>
					<view class="info">
						<view>来访者:</view>
						<view>{{ personInfo.recordName }}</view>
					</view>
					<view class="info">
						<view>咨询日期:</view>
						<view>{{ dataObj.appointmentDate }}</view>
					</view>
					<view class="info">
						<view>咨询时间:</view>
						<view>{{ dataObj.startTime }}-{{ dataObj.endTime }}</view>
					</view>
					<view class="info">
						<view>咨询时长:</view>
						<view>{{ calculateTimeDifference(`${dataObj.startTime}-${dataObj.endTime}`) }}</view>
					</view>
					<view class="info">
						<view>问题类型:</view>
						<view>{{ experInfo.domainName }}</view>
					</view>
				</view>
			</scroll-view>
		</view>
		<view class="bot-btn">
			<view>
				<text>咨询费：</text>
				<text>¥</text>
				<text>{{ dataObj.amount }}</text>
			</view>
			<view class="activeBtn" @click="handlePay">
				<text>支付</text>
				<text>剩({{timeShow}})</text>
				<!-- <u-count-down @change="onChange" format="DD:HH:mm:ss" millisecond :time="endTime" :auto-start="false">
					<view class="time">
						<text>(剩</text>
						<text class="time__item">{{ timeData.minutes }}&nbsp;分</text>
						<text class="time__item">{{ timeData.seconds }}&nbsp;秒</text>
						<text>)</text>
					</view>
				</u-count-down> -->
			</view>
		</view>
	</view>
</template>

<script>
	import {
		editAppointment,
		appointmentDetail,
		getExpert,
		consultationRecord
	} from '@/api/consult/index.js';
	export default {
		data() {
			return {
				domHeight: '',
				current: '3',
				id: '',
				dataObj: {},
				experInfo: {},
				personInfo: {},
				fromPage: '',
				orderCreateTime: '', // 订单创建时间戳（毫秒）
				timeShow: '15分0秒',
				timer: null
			};
		},
		onLoad(options) {
			// department_phone 
			this.id = options.id;
			appointmentDetail(this.id).then((res) => {
				this.dataObj = res.data;
				this.orderCreateTime = res.data.createTime;
				let time = ''
				this.timer = setInterval(()=>{
					time = this.calculateTimeDifferenceCopy(this.orderCreateTime);
					if(time&&time>1000){
						this.timeShow = this.formatMilliseconds(time)
					}else if(time < 1000){
						this.timeShow = '0'
						clearInterval(this.timer);
						this.$u.toast('订单已取消');
						setTimeout(()=>{
							uni.switchTab({
								url:'/pages/consult/index'
							})
						},1000)
					}
				},1000)

				//查询专家信息
				getExpert(res.data.expertId).then((res) => {
					this.experInfo = res.data;
				});
				//查询档案
				consultationRecord(res.data.recordId).then((res) => {
					this.personInfo = res.data;
				});
			});

			const pages = getCurrentPages();
			if (pages.length > 1) {
				const prevPage = pages[pages.length - 2];
				this.fromPage = prevPage.route;
			}
		},
		methods: {
			handlePay() {
				uni.showLoading({
				  title: '支付中...',
				  mask: true // 防止触摸穿透
				});
				editAppointment({
					id: this.id
				}).then((resa) => {
					wx.requestPayment({
						appId: resa.data.appId,
						nonceStr: resa.data.nonceStr,
						package: resa.data.packageVal,
						paySign: resa.data.paySign,
						signType: resa.data.signType,
						timeStamp: resa.data.timeStamp,
						success: (res) => {
							uni.hideLoading();
							this.$modal.showToast('支付成功');
							setTimeout(() => {
								this.$tab.switchTab(`/pages/consult/index`);
							}, 800);
						},
						fail: (err) => {
							this.$modal.showToast('支付失败');
							uni.hideLoading();
						}
					});
				});
			},
			leftClick() {
				// if (this.fromPage === 'subset/pages/consult/consultOrder/consultOrder') {
				// 	this.$tab.navigateTo(`/subset/pages/consult/consultOrder/consultOrder?id=${this.id}`);
				// } else {
				// 	this.$tab.navigateBack();
				// }
				const consultData = JSON.parse(uni.getStorageSync('consultData'))
				this.$tab.redirectTo(`/subset/pages/consult/consultDetail?id=${consultData.experId}`)
			},
			onChange(e) {
				this.timeData = e;
				// console.log(e);
				// this.$u.toast('订单已取消');
			},
			formatMilliseconds(ms) {
				const totalSeconds = Math.floor(ms / 1000);
				const minutes = Math.floor(totalSeconds / 60);
				const seconds = totalSeconds % 60;

				return `${minutes}分${String(seconds).padStart(2, '0')}秒`;
			},
			calculateTimeDifferenceCopy(inputTimeStr) {
				try {
					// 1. 解析输入时间（兼容常见格式）
					// let date = new Date(inputTimeStr.replace(/ /g, 'T') + 'Z'); // 转换为ISO格式并强制UTC解析

					// // 2. 验证时间有效性
					// if (isNaN(date)) throw new Error('Invalid date format');

					// // 3. 添加15分钟
					// const newDate = new Date(date.getTime() + 15 * 60 * 1000);

					// // 4. 获取当前时间戳
					// const now = Date.now();

					// // 5. 时间差计算（毫秒）
					// const diff = newDate.getTime() - now;
					
					const target = new Date(inputTimeStr).getTime() + 15 * 60 * 1000;
					const current = Date.now();
					const diff = target - current;
					// console.log('时间差：', target - current); // 应为正值（未超时）或负值（已超时）

					// 6. 返回结果判断
					return diff > 0 ? diff : 0;

				} catch (error) {
					console.warn('时间计算错误:', error.message);
					return 0; // 异常情况返回0
				}
			},
			calculateTimeDifference(timeRange) {
				// 分割时间段为开始和结束时间
				const [start, end] = timeRange.split('-');

				// 将时间转换为分钟数
				const startMinutes = this.convertToMinutes(start);
				const endMinutes = this.convertToMinutes(end);

				// 计算时间差（分钟）
				const diff = endMinutes - startMinutes;

				// 转换为小时和分钟
				const hours = Math.floor(diff / 60);
				const minutes = diff % 60;

				// 构建结果字符串
				let result = '';
				if (hours > 0) {
					result += `${hours}小时`;
				}
				if (minutes > 0) {
					result += `${minutes}分钟`;
				}

				return result || '0分钟'; // 处理0分钟的情况
			},

			// 辅助函数：将时间字符串转换为分钟数
			convertToMinutes(timeStr) {
				const [hours, mins] = timeStr.split(':').map(Number);
				return hours * 60 + mins;
			},
			formatTimestamp(ts, format = 'YYYY-MM-DD HH:mm:ss') {
				const date = new Date(ts);
				const pad = (n) => n.toString().padStart(2, '0');

				const map = {
					YYYY: date.getFullYear(),
					MM: pad(date.getMonth() + 1),
					DD: pad(date.getDate()),
					HH: pad(date.getHours()),
					mm: pad(date.getMinutes()),
					ss: pad(date.getSeconds())
				};

				return format.replace(/YYYY|MM|DD|HH|mm|ss/g, (match) => map[match]);
			}
		},
		mounted() {
			const systemInfo = uni.getSystemInfoSync();
			let statusBarHeight = systemInfo.statusBarHeight || 20;
			// 示例计算公式（具体需根据组件实现调整）
			const height = statusBarHeight + 44 + 'px'; // 状态栏高度 + 导航栏内容高度
			this.domHeight = `calc(100% - ${height} - 150rpx - 166rpx)`;
		},
		onUnload() {
			clearInterval(this.timer);
		}
	};
</script>

<style lang="scss">
	.payment {
		width: 100%;
		height: 100%;
		overflow: hidden;
		background-color: rgb(232, 234, 239);

		.process {
			width: 100%;
			height: 150rpx;
			display: flex;
			align-items: center;
			background-color: #fff;

			::v-deep .u-steps-item__wrapper {
				width: 20px;
				height: 20px;
				border-radius: 50%;
				background-color: #fafafa;
			}

			::v-deep .u-steps-item__wrapper__circle__text {
				color: #fff !important;
			}
		}

		.cantainer {
			width: 100%;
			margin: auto;
			padding: 20rpx 18rpx;
			overflow: hidden;

			.scrollWrap {
				width: 100%;
				height: 100%;

				.dot-show {
					width: 100%;
					box-sizing: border-box;
					border-radius: 20rpx;
					padding: 30rpx;
					box-sizing: border-box;
					height: 260rpx;
					background-color: #fff;
					position: relative;
					display: flex;

					>image {
						width: 160rpx;
						height: 200rpx;
						border-radius: 10rpx;
					}

					>view:nth-child(2) {
						width: calc(100% - 160rpx);
						padding: 20rpx 0 20rpx 40rpx;
						display: flex;
						flex-wrap: wrap;
						align-content: space-around;

						>view:nth-child(1) {
							width: 100%;
							font-size: 30rpx;
							color: #000;
							font-weight: bold;
						}

						>view:nth-child(2),
						view:nth-child(3) {
							width: 100%;
							font-size: 24rpx;
							color: #a8a8a8;
						}
					}

					>view:last-child {
						position: absolute;
						right: 0;
						top: 0;
						width: 150rpx;
						height: 60rpx;
						line-height: 60rpx;
						text-align: center;
						font-size: 26rpx;
						background-color: #ffefbf;
						color: #ffaa00;
						border-top-right-radius: 20rpx;
					}
				}

				.appointInfo {
					width: 100%;
					padding: 40rpx 30rpx;
					margin-top: 20rpx;
					background-color: #fff;
					border-radius: 20rpx;

					>view:first-child {
						width: 100%;
						font-size: 32rpx;
						font-weight: bold;
						color: #000;
					}

					.info {
						width: 100%;
						display: flex;
						margin-top: 40rpx;

						>view {
							font-size: 28rpx;
						}

						>view:nth-child(1) {
							width: 150rpx;
							color: #a8a8a8;
						}

						>view:nth-child(2) {
							width: calc(100% - 150rpx);
							color: #000;
						}
					}
				}
			}
		}

		.bot-btn {
			width: 100%;
			height: 166rpx;
			position: fixed;
			bottom: 0;
			left: 0;
			background-color: #fff;
			padding: 30rpx 30rpx 30rpx 0;
			box-sizing: border-box;
			display: flex;
			justify-content: space-between;

			>view:nth-child(1) {
				width: 50%;
				height: 106rpx;
				text-align: center;
				line-height: 106rpx;
				display: flex;
				align-items: center;
				justify-content: center;

				>text:nth-child(1) {
					color: #444444;
					font-size: 26rpx;
				}

				>text:nth-child(2) {
					color: #ffaa00;
					font-size: 26rpx;
				}

				>text:nth-child(3) {
					color: #ffaa00;
					font-size: 50rpx;
					margin-left: 10rpx;
				}
			}

			>view:nth-child(2) {
				width: 50%;
				height: 106rpx;
				text-align: center;
				line-height: 106rpx;
				background: #e7e7e7;
				color: #bcbcbc;
				font-size: 32rpx;
				border-radius: 50rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.activeBtn {
				background: #5c83fd !important;
				color: #fff !important;
			}
		}
	}
</style>